﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class EditForm : Form
    {
        public EditForm()
        {
            InitializeComponent();
        }
        //帮助更新
        public EditForm(int id,string name,int age,int score)
        {
            InitializeComponent();
            this.id = id;
            txtName.Text = name;
            txtAge.Text = age.ToString();
            txtScore.Text = score.ToString();
        }

        private int id;

        /// <summary>
        /// 保存信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            var ageString = txtAge.Text.ToString();
            var scoreString = txtScore.Text.ToString();
            //姓名不为空
            var name = txtName.Text;
            var boolName = !string.IsNullOrEmpty(name);
            //默认年龄为18，分数为0
            var age = ageString.Count() > 0 ? int.Parse(ageString) : 18;
            var score = scoreString.Count() > 0 ? int.Parse(scoreString) : 0;
            //更新
            if (id > 0)
            {
                if (boolName)
                {
                    var sql = string.Format("update Students set Name='{0}',Age='{1}',Score='{2}' where Id={3}",name,age,score,this.id);
                    var res = DbHelper.AddOrAddOrEditOrDeleteSave(sql);

                    if (res == 1)
                    {
                        MessageBox.Show("更新成功!", "提示");
                        this.DialogResult = DialogResult.Yes;
                        this.Close();
                    }
                }
            }
            //新增
            else 
            {

                if (boolName)
                {
                    var sql = string.Format("insert into Students(name,Age,Score)values('{0}','{1}','{2}')", name, age, score);

                    var res = DbHelper.AddOrAddOrEditOrDeleteSave(sql);

                    if (res == 1)
                    {
                        MessageBox.Show("添加成功!", "提示");
                        this.DialogResult = DialogResult.Yes;
                        this.Close();
                    }
                }
                else
                {
                    MessageBox.Show("学生姓名不能为空!", "提示");
                    this.Close();
                }
            }
        }
        /// <summary>
        /// 取消保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.No;
            this.Close();
        }
    }
}
